package top.huntwolf.admin.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import top.huntwolf.admin.common.enums.EnumValue;

public final class StringToEnumConverterFactory implements ConverterFactory<String, EnumValue> {

    @Override
    public <T extends EnumValue> Converter<String, T> getConverter(Class<T> aClass) {
        return new StringToEnum(aClass);
    }

    private class StringToEnum<T extends Enum<T> & EnumValue> implements Converter<String,T>{

        private final Class<T> enumType;

        public StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) {
            source = source.trim();
            return source.isEmpty() ? null : EnumValue.valueOf(this.enumType,source);
        }
    }
}
